package com.quick.android.handler.image;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.ImageDownloader.Scheme;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.quick.android.app.AppConfig;
import com.quick.android.utils.AppUtils;
import com.quick.android.utils.CheckUtils;

import java.io.File;

public class ImageLoadHandler {
    private static ImageLoadHandler mInstance;
    /**
     * 是否可以加载图片<br>
     * 当没有加载存储卡时，默认不加载图片，只显示默认图
     */
    public static boolean isCanLoad = true;
    private Context mContext;
    private ImageLoader mImageLoader;
    private DisplayImageOptions mDefaultOptions;
    private DisplayImageOptions mLargerOptions;

    public static ImageLoadHandler getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new ImageLoadHandler(context);
        }
        return mInstance;
    }

    private ImageLoadHandler(Context context) {
        mContext = context.getApplicationContext();
        mImageLoader = ImageLoader.getInstance();
        initImageLoader(mContext);
    }

    private void initImageLoader(Context context) {
        isCanLoad = AppUtils.isSdcardWritable();
        ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
                context).threadPriority(Thread.NORM_PRIORITY - 2)
                .threadPoolSize(AppConfig.DEFAULT_THREAD_COUNT)
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new WeakMemoryCache())
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .memoryCacheSize(AppConfig.MEMORY_CACHE_SIZE).diskCacheSize(AppConfig.DISK_CACHE_SIZE)
                .tasksProcessingOrder(QueueProcessingType.LIFO);
        if (isCanLoad) {
            File cacheDir = new File(AppConfig.getCacheImgDir(context));
            builder.diskCache(new UnlimitedDiscCache(cacheDir));
        }
        if (AppConfig.IS_DEBUG) {
            builder.writeDebugLogs();
        }
        ImageLoaderConfiguration config = builder.build();
        mImageLoader.init(config);
        setOptions();
        setLargerOptions();
    }

    /**
     * 在内存不够用时，可以清除缓存，减小APP内存压力
     */
    public void clearCache() {
        mImageLoader.clearMemoryCache();
    }

    /**
     * 加载普通图片的Options设置
     */
    private void setOptions() {
        mDefaultOptions = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true).considerExifParams(true).build();
    }

    /**
     * 加载大图的Options设置
     */
    private void setLargerOptions() {
        mLargerOptions = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true).considerExifParams(true).build();
    }

    /**
     * 读取本地文件名
     */
    public String getFileUri(String imagePath) {
        return Scheme.FILE.wrap(imagePath);
    }

    /**
     * 读取Assets文件名
     */
    public String getAssetsUri(String imagePath) {
        return Scheme.ASSETS.wrap(imagePath);
    }

    /**
     * 读取Drawable资源id文件名
     */
    public String gtetDrawableUri(String drawableName) {
        return Scheme.DRAWABLE.wrap(drawableName);
    }

    /**
     * 加载正常网络图片
     */
    public void loadHttpImage(final ImageView mImageView, final String url,
                              int width, int height) {
        loadHttpImage(mImageView, url, width, height, false);
    }

    /**
     * 加载网络图片
     */
    public void loadHttpImage(final ImageView mImageView, final String url,
                              int width, int height, boolean isLargerImage) {
        if (isLargerImage) {
            loadImage(mImageView, url, width, height, mLargerOptions);
        } else {
            loadImage(mImageView, url, width, height, mDefaultOptions);
        }
    }

    /**
     * 加载本地正常图片
     */
    public void loadFileImage(ImageView mImageView, final String filePath, int width, int height) {
        loadFileImage(mImageView, getFileUri(filePath), width, height, false);
    }

    /**
     * 加载本地图片
     */
    public void loadFileImage(ImageView mImageView, String filePath, int width, int height, boolean isLargerImage) {
        if (isLargerImage) {
            loadImage(mImageView, getFileUri(filePath), width, height, mLargerOptions);
        } else {
            loadImage(mImageView, getFileUri(filePath), width, height, mDefaultOptions);
        }
    }

    /**
     * 加载Assert文件夹中的图片
     */
    public void loadAssetImage(ImageView mImageView, String filePath, int width, int height) {
        loadAssetImage(mImageView, filePath, width, height, false);
    }

    /**
     * 加载Assert文件夹中的图片
     */
    public void loadAssetImage(ImageView mImageView, String filePath, int width, int height, boolean isLargerImage) {
        if (isLargerImage) {
            loadImage(mImageView, getAssetsUri(filePath), width, height, mLargerOptions);
        } else {
            loadImage(mImageView, getAssetsUri(filePath), width, height, mDefaultOptions);
        }
    }

    /**
     * 加载资源图片
     */
    public void loadResourceImage(ImageView mImageView, String drawableName, int width, int height) {
        loadResourceImage(mImageView, drawableName, width, height, false);
    }

    /**
     * 加载资源图片
     */
    public void loadResourceImage(ImageView mImageView, String drawableName, int width, int height, boolean isLargerImage) {
        if (isLargerImage) {
            loadImage(mImageView, gtetDrawableUri(drawableName), width, height, mLargerOptions);
        } else {
            loadImage(mImageView, gtetDrawableUri(drawableName), width, height, mDefaultOptions);
        }
    }

    /**
     * 加载图片
     */
    public void loadImage(final ImageView mImageView, final String url,
                          int width, int height, DisplayImageOptions option) {
        if (mImageView == null || CheckUtils.isStrEmpty(url)) {
            return;
        }
        final Drawable loadingDrawable = option.getImageOnLoading(mContext
                .getResources());
        if (!isCanLoad) {
            mImageView.setImageDrawable(loadingDrawable);
            return;
        }
        mImageView.setTag(url);
        ImageSize size = new ImageSize(width, height);
        mImageLoader.loadImage(url, size, option, new ImageLoadingListener() {

            @Override
            public void onLoadingCancelled(String arg0, View arg1) {
                mImageView.setImageDrawable(loadingDrawable);
            }

            @Override
            public void onLoadingComplete(String arg0, View arg1, Bitmap bitmap) {
                mImageView.setImageBitmap(bitmap);
            }

            @Override
            public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
                mImageView.setImageDrawable(loadingDrawable);
            }

            @Override
            public void onLoadingStarted(String arg0, View arg1) {
                mImageView.setImageDrawable(loadingDrawable);
            }
        });
    }

    /**
     * 优化AbsListView滑动时加载图片问题,适用于ListView、GridView
     */
    public void optAbsListViewScroll(AbsListView view, boolean pauseOnScroll,
                                     boolean pauseOnFling) {
        if (view == null) {
            return;
        }
        view.setOnScrollListener(new PauseOnScrollListener(mImageLoader,
                pauseOnScroll, pauseOnFling));
    }

}
